package cn.my.framework.common.service;

import cn.my.framework.common.entity.*;
import cn.my.framework.common.mapper.UserMapper;
import cn.my.framework.common.repo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import javax.transaction.Transactional;

/**
 * Created by zhangl_lc on 2017/7/6.
 */
@Service
public class UserPermService {
    @Autowired
    UserRepo userRepo;
    @Autowired
    RoleRepo roleRepo;
    @Autowired
    PermissionRepo permRepo;
    @Autowired
    UserRoleRepo urRepo;
    @Autowired
    RolePermRepo rpRepo;
    @Autowired
    UserMapper userMapper;

    @Transactional
    public boolean saveUser(User user){
        userRepo.save(user);
        return true;
    }

    @Transactional
    public boolean saveRole(Role role){
        roleRepo.save(role);
        return true;
    }

    public User findUser(String code){
        return userRepo.findByCode(code);
    }

    public List<UserRole> listUserRoles(){
        return urRepo.findAll();
    }

    public List<RolePerm> listRolePerms(){
        return rpRepo.findAll();
    }

    public Page<User> selectUsersForPageTest(){
        Page<User> page = PageHelper.startPage(1,3);
        userMapper.selectUsers();
        return page;
    }

    public Page<User> selectUsers(int pageNum,int pageSize){
        Page<User> page = PageHelper.startPage(pageNum,pageSize);
        userMapper.selectUsers();
        return page;
    }

    public List<Map<String,String>> listMenuPermsWithRole(){
        List<Map<String,String>> list = new ArrayList<>();
        rpRepo.selectPerms().forEach(p ->{
            list.add(new HashMap<String,String>(){{
                put("permCode",(String)p[0]);
                put("url",(String)p[1]);
                put("roleCode",(String)p[2]);
            }});
        });
        return list;
    }

    public List<Role> listRoles(String userCode){
        return roleRepo.selectByUserCode(userCode);
    }

    public List<Permission> listPermsByRole(String roleCode){
        return permRepo.selectByRoleCode(roleCode);
    }

    public List<Permission> listPermsByUser(String userCode){
        return permRepo.selectByUserCode(userCode);
    }
}
